
<template>
    <div class="common-layout">
        <el-container>
            <el-aside width="50px"></el-aside>
            <el-main>
                <div class="d-clo" style="height: 100%; overflow: hidden">
                    <div style="height: 150px; width: 100%">
                        <div class="d-flex d-jc-between sinBox">
                            <div class="d-flex">
                                <div class="d-flex d-ai-center d-jc-center">
                                    <el-avatar :src="users.userMessage.avatar" :size="80" />
                                </div>
                                <div class="margin-left-10">
                                    <div class="margin-top-10 margin-bottom-10 font22" style="font-weight: bold;">{{ users.userMessage.name }}</div>
                                    <div class="margin-top-10 margin-bottom-10 font12">{{ getDayJS(parseInt(users.userMessage.timestamp) * 1000, 'YYYY-MM-DD HH:mm:ss') }}</div>
                                    <div>
                                        <el-icon @click="loadUserData"><RefreshRight /></el-icon>
                                        <el-icon class="margin-left-10" @click="directMessage2(pkId, users.userMessage.name)"><Download /></el-icon>
                                    </div>
                                </div>
                            </div>
                            <div style="width: 100px; height: 100px">
                                <VueQrcode :value="users.url" :width="100" color-dark="#000000" color-light="#FFFFFF" v-if="users.url"></VueQrcode>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex-1 no-scrollbar" style="height: 250px">
                        <div>
                            <div v-for="item in users.userList" :key="item.pkId" class="margin-bottom-10 sinBox">
                                <div class="d-flex d-ai-center">
                                    <div class="d-flex d-ai-center d-jc-between" style="width: 100%">
                                        <div class="d-flex d-ai-center">
                                            <el-avatar :src="item.avatar" />
                                            <div class="margin-left-10">{{ item.name }}</div>
                                        </div>
                                        <el-icon @click="directMessage1(item.mid, item.talkerId, item.name)"><Download /></el-icon>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-main>
            <el-aside width="50px"></el-aside>
        </el-container>
    </div>
</template>

  <script setup>
import { ref, reactive, watch, watchEffect, onUnmounted } from 'vue'
import VueQrcode from 'vue-qrcode'
import axios from 'axios'
import { existsSync, errorPath, getAllLink, getLink } from '@/utils/electron.ts'
import { myUser, getQrCode, getPoll, postBilibiliMessage } from '@/api/bilibibili/index.js'
import store from '@/utils/localStore.ts'
import { getDayJS, getDayNum } from '@/utils/dayJs.ts'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { useRoute } from 'vue-router'

const route = useRoute()
// const pkId = '406378249'
const pkId = route.query.mid

let loading = ref(false)

let users = reactive({
    qrcode_key: '',
    url: '',
    token: '',
    mainList: [],
    userList: [],
    userMessage: {
        avatar: '',
        face: '',
        mid: 123456,
        uname: '666',
        timestamp: '1744180830'
    },
    markdownContent: ``,
    mid: 0
})

let intervalId = ref(null)
let config = reactive({
    headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36'
    }
})

const markdownContent = ref('')

const getInit = () => {
    let token = store.getItem(pkId) || null
    if (token) {
        users.token = token
        getUserList()
    } else {
        getQrCode().then((res) => {
            if (res.code == 200) {
                users.url = res.data.url
                users.qrcode_key = res.data.qrcode_key
                intervalId.value = setInterval(timerFunction, 1000)
            }
        })
    }
}

const timerFunction = () => {
    let params = {
        qrcode_key: users.qrcode_key
    }
    getPoll(params).then((res) => {
        if (res.code == 200) {
            if (res.data.code == 200) {
                clearInterval(intervalId.value)
                intervalId.value = null
                users.token = res.data.token
                users.url = ''
                getUserList()
            }
        }
    })
}

const getUserList = () => {
    let params = {
        token: users.token
    }
    myUser(params).then((res) => {
        if (res.code == 200) {
            // users.userMessage = res.data
            if (res.data.mid == pkId) {
                store.setItem(res.data.mid, users.token)
            }
            getMeUser(res.data.mid)
        } else {
            getQrCode().then((res) => {
                if (res.code == 200) {
                    users.url = res.data.url
                    users.qrcode_key = res.data.qrcode_key
                    intervalId.value = setInterval(timerFunction, 1000)
                }
            })
        }
    })
}

const getMainList = async (mid = '') => {
    // let link = `select * from mainUser where mid = ${mid}`
    let link = `SELECT a.*,b.timestamp FROM mainUser a LEFT JOIN biLiMessage b ON a.mid = b.mid  WHERE a.mid = ${mid} ORDER BY b.timestamp DESC LIMIT 1;`
    try {
        const data = await getLink(link)
        users.userMessage = data
        getMeUser(mid)
    } catch (err) {}
}

const getMeUser = async (mid) => {
    let link = `select * from biLiUser where mid = ${mid} order by pkId desc`
    try {
        loading.value = true
        const data = await getAllLink(link)
        users.userList = data
    } catch (err) {
        loading.value = false
    }
}

const directMessage = async (mid, talkerId, name = '') => {
    let link = `select a.*, b.name as sname from biLiMessage a left join biliUser b on a.senderUid = b.talkerId where a.mid = ${mid} and (a.senderUid = ${talkerId} or a.receiverId = ${talkerId}) order by a.timestamp desc`
    try {
        const data = await getAllLink(link)
        return data
    } catch (err) {}
}

const directMessage1 = async (mid, talkerId, name = '') => {
    let data = await directMessage(mid, talkerId, name)
    users.markdownContent = ''
    users.markdownContent += `### ${name}  \n\n`
    data.forEach((item) => {
        let lname = getName(mid, item.senderUid, item.receiverId, name, users.userMessage.name)
        item.lname = lname
        users.markdownContent += `  ${getDayJS(parseInt(item.timestamp) * 1000, 'YYYY-MM-DD HH:mm:ss')}\n`
        users.markdownContent += `  **${lname}**\n`
        users.markdownContent += `  ${getContent(item.content)}\n\n`
        
    })
    downloadMarkdown(name)
}

const directMessage2 = async (mid, name) => {
    let link = `select * from biLiUser where mid = ${mid} order by pkId desc`
    try {
        const data = await getAllLink(link)
        users.markdownContent = ''
        for (let item of data) {
            item.list = await directMessage(mid, item.talkerId)
        }
        data.forEach((item) => {
            users.markdownContent += `### ${item.name}  \n\n`
            item.list.forEach((item2) => {
                let lname = getName(mid, item2.senderUid, item2.receiverId, item.name, name)
                item2.lname = lname
                users.markdownContent += `  ${getDayJS(parseInt(item2.timestamp) * 1000, 'YYYY-MM-DD HH:mm:ss')}\n`
                users.markdownContent += `  **${lname}**\n`
                users.markdownContent += `  ${getContent(item2.content)}\n\n`
            })
        })
        downloadMarkdown(name)
    } catch (err) {}
}

const getName = (mid, senderUid, receiverId ,sname, rname) => {
    if(mid == senderUid) {
        return rname
    } else {
        return sname
    }
}

const getContent = (content) => {
    let con = ''
    let contentJOSN = JSON.parse(content)
    if (contentJOSN.content) {
        con = contentJOSN.content
    } else if (contentJOSN.url) {
        con = `![图片](${contentJOSN.url})`
    }
    return con
}


const downloadMarkdown = (name = 'document') => {
    const blob = new Blob([users.markdownContent], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${name}.md` // 设置下载文件名
    a.click()
    URL.revokeObjectURL(url)
}

const loadUserData = () => {
    let params = {
        token: users.token
    }
    postBilibiliMessage(params).then((res) => {
        if (res.code == 200) {
            ElMessage({
                message: '私聊数据正在更新',
                type: 'success'
            })
        }
    })
}

// getUserList()
getMainList(pkId)
getInit()

onUnmounted(() => {
    if (intervalId.value) {
        clearInterval(intervalId.value)
        intervalId.value = null
    }
})
</script>

<style scoped>
.common-layout {
    height: 100%;
}

.el-main {
    padding: 0px;
    height: 100vh;
    overflow-y: auto;
}

.sinBox {
    border-radius: 5px;
    padding: 10px;
    border: 1px solid #e4e7ed;
    box-shadow: 2px 2px 3px #e4e7ed;
}
</style>
  